package protocol.work.connection.http.wlwx;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import protocol.data.util.JedisPoolUtil;
import protocol.work.SystemManager;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class HttpReadReportListener extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected String report_pre_fix;
	
	protected JedisPool jedisPool;
	
	public void init() throws ServletException {
		this.jedisPool = JedisPoolUtil.getJedisPool();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Jedis jedis = this.jedisPool.getResource();
		try{
			Calendar cal = Calendar.getInstance();
		    int day = cal.get(Calendar.DATE);
		    int month = cal.get(Calendar.MONTH) + 1;
			String reportListStr = request.getParameter("report");
			if(reportListStr!=null && reportListStr.length()>0){
				String[] reportStr = reportListStr.split("\\^");
				for(String report : reportStr){
					Map<String,String> reportMap = new HashMap<String,String>();
					String[] reportItems = report.split(",");
					reportMap.put("MSG_ID", reportItems[0]);
					reportMap.put("MOBILE", reportItems[1]);
					reportMap.put("REPORT_STATUS", reportItems[2].equals("DELIVRD")?"0":"255");
					reportMap.put("REPORT_DESC", reportItems[2]);
					reportMap.put("REPORT_RESULT", reportItems[2].equals("DELIVRD")?"5":"4");
					reportMap.put("REPORT_TIME", reportItems[3]);
					reportMap.put("MONTH",month+"");
					reportMap.put("DAY", day+"");
					reportMap.put("DataType", "Report");
					String mapKey = "Report-"+reportItems[0];
					jedis.hmset(mapKey, reportMap);
					jedis.lpush(SystemManager.report_per_fix, mapKey);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			if (jedis != null)
				if (jedis.isConnected())
					this.jedisPool.returnResource(jedis);
				else
					this.jedisPool.returnBrokenResource(jedis);
		}
	}

	public static void main(String[] args) {
		String reportListStr = "32 DAY:9 REPORT_TIME:2016-03-09 16:26:25^";
		String[] reportStr = reportListStr.substring(0,reportListStr.length()-1).split("\\^");
		for(String report : reportStr){
			System.out.println(report);
		}
	}
	
}
